package com.xxl.job.admin.core.conf;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class LdapLogin {
    @Value("${extension.ldap.host:}")
    private String host;
    @Value("${extension.ldap.port:}")
    private String port;
    @Value("${extension.ldap.domain:}")
    private String domain;

    public boolean check(String userName, String password) {
        String url = new String("ldap://" + host + ":" + port);
        String user = String.format("%s@%s", userName, domain);

        Hashtable<String, Object> env = new Hashtable<String, Object>();
        env.put(Context.SECURITY_AUTHENTICATION, "simple");//一种模式，不用管，就这么写就可以了
        env.put(Context.SECURITY_PRINCIPAL, user);
        env.put(Context.SECURITY_CREDENTIALS, password);
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, url);
        DirContext ctx = null;
        try {
            ctx = new InitialDirContext(env);
            return Boolean.TRUE;
        } catch (Exception err) {
            return Boolean.FALSE;
        } finally {
            try {
                if (ctx != null) {
                    ctx.close();
                }
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
    }
}
